<template>
	<view class="product-detail-container page-container-with-bottom-btn">
		<!-- 商品图片轮播 -->
		<view class="product-images">
			<swiper class="swiper" :current="currentImageIndex" :indicator-dots="true" :autoplay="false"
				:interval="3000" :duration="1000" @change="onSwiperChange">
				<swiper-item v-for="(item, index) in dataInfo.main_images" :key="index">
					<image :src="$tools.buildUrl(item.url)" mode="aspectFill" class="swiper-image"
						@click="previewImage(item.url)"></image>
				</swiper-item>
			</swiper>
			<!-- 缩略图 -->
			<view class="thumbnail-list">
				<view class="thumbnail-item" v-for="(item, index) in dataInfo.main_images" :key="index"
					:class="{ active: currentImageIndex === index }" @click="switchImage(index)">
					<image :src="$tools.buildUrl(item.url)" mode="aspectFill" class="thumbnail-image"></image>
				</view>
			</view>
		</view>

		<!-- 商品基本信息 -->
		<view class="product-info">
			<view class="product-title">{{ dataInfo.spu_name }}</view>
			<view class="price-section">
				<text class="price-label">价格</text>
			</view>
			<view class="price-value">
				<text class="current-price">¥{{ unit_price }}元</text>
			</view>
			<!-- <view class="activity-section" v-if="dataInfo.activity">
				<text class="activity-label">活动</text>
			</view> -->
			<!-- <view class="activity-content" v-if="dataInfo.activity">
				<text class="activity-text">{{ dataInfo.activity }}</text>
			</view> -->
		</view>

		<!-- 规格选择 -->
		<view class="spec-section">
			<view class="spec-header">
				<text class="spec-label">规格</text>
			</view>
			<view v-if="dataInfo.spu_type===0" class="spec-options">
				<view class="spec-option" v-for="(spec, index) in dataInfo.skuArray" :key="index"
					:class="{ active: selectedSpecs === index }" @click="selectSpec(index)">
					<text class="spec-text">{{ spec.sku_name }}</text>
				</view>
			</view>
			<block v-else>
				<view v-for="(spec, index) in dataInfo.skuArray" :key="index" class="spec-combo"
					:class="{ active: selectedSpecs === index }" @click="selectSpec(index)">
					<text class="combo-text">{{ spec.sku_name }}</text>
				</view>
			</block>
		</view>

		<!-- 配送方式 -->
		<view class="delivery-section">
			<view class="delivery-header">
				<text class="delivery-label">配送方式</text>
			</view>
			<view class="delivery-options">
				<view class="delivery-option" v-for="(option, index) in deliveryOptions" :key="index"
					:class="{ active: selectedDelivery === index }" @click="selectDelivery(index)">
					<text class="delivery-text">{{ option.label }}</text>
				</view>
			</view>
		</view>
		<view class="delivery-section">
			<view class="section-title">线下门店</view>
			<view class="delivery-options">
				<view class="delivery-option active" @click="toUnlineStore">
					查看自提门店
				</view>
			</view>
		</view>

		<!-- 发货信息 -->
		<view v-if="defaultAddress.id && defaultAddress.id!==''" class="shipping-section">
			<view class="shipping-header">
				<text class="shipping-label">发货</text>
			</view>
			<view class="shipping-content">
				<text class="shipping-text">配送至：{{ defaultAddress.city.name }}{{ defaultAddress.town.name }}</text>
			</view>
			<view class="shipping-content">
				<text v-if="shippingFee>=0" class="shipping-text">
					普通快递：<text style="color:#ff0000; margin: 0 3px;">{{shippingFee }}</text>元
				</text>
				<text v-if="shippingDesc && shippingDesc!==''" class="shipping-text" style="padding-left: 8px;">
					| {{ shippingDesc }}</text>
			</view>
		</view>

		<!-- 数量选择 -->
		<view class="quantity-section">
			<view class="quantity-header">
				<text class="quantity-label">数量</text>
			</view>
			<view class="quantity-control">
				<button class="quantity-btn decrease" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
				<text class="quantity-value">{{ quantity }}</text>
				<button class="quantity-btn increase" @click="increaseQuantity">+</button>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-actions fixed-bottom-safe">
			<view class="action-left">
				<view class="action-item" @click="addToFavorites">
					<image src="@/static/tabbar/home.png" class="action-icon"></image>
					<text class="action-text">收藏</text>
				</view>
				<button open-type="contact" class="action-item">
					<image src="@/static/images/user/member-service.jpg" class="action-icon">
					</image>
					<text class="action-text">客服</text>
				</button>
				<view class="action-item" @click="viewCart">
					<image src="@/static/tabbar/cart.png" class="action-icon"></image>
					<text class="action-text">购物车</text>
				</view>
			</view>
			<view class="action-right">
				<button class="add-cart-btn" @click="showSpecPopup = true">加入购物车</button>
				<button class="buy-now-btn" @click="showSpecPopup = true">立即购买</button>
			</view>
		</view>

		<!-- 规格选择弹窗 -->
		<u-popup :show="showSpecPopup" mode="bottom" border-radius="20" :safe-area-inset-bottom="true"
			@close="closeSpecPopup">
			<view class="spec-popup">
				<view class="popup-header">
					<text class="popup-title">规格</text>
					<u-icon name="close" size="20" @click="closeSpecPopup"></u-icon>
				</view>

				<!-- 规格选择 -->
				<view class="spec-section">
					<view v-if="dataInfo.spu_type===0" class="spec-group">
						<view class="spec-options">
							<view class="spec-option" v-for="(spec, index) in dataInfo.skuArray" :key="index"
								:class="{ active: selectedSpecs === index }" @click="selectSpec(index)">
								{{ spec.sku_name }}
							</view>
						</view>
					</view>
					<block v-else>
						<view v-for="(spec, index) in dataInfo.skuArray" :key="index" class="spec-combo"
							:class="{ active: selectedSpecs === index }" @click="selectSpec(index)">
							<text class="combo-text">{{ spec.sku_name }}</text>
						</view>
					</block>
				</view>

				<!-- 配送方式 -->
				<view class="delivery-section">
					<view class="section-title">配送方式</view>
					<view class="delivery-options">
						<view class="delivery-option" v-for="(delivery, index) in deliveryOptions" :key="index"
							:class="{ active: selectedDelivery === index }" @click="selectDelivery(index)">
							{{ delivery.label }}
						</view>
					</view>
				</view>

				<!-- 发货地址 -->
				<view v-if="defaultAddress.id && defaultAddress.id !== ''" class="address-section">
					<view class="section-title">发货</view>
					<text class="address-text">配送至：{{ defaultAddress.city.name }}{{ defaultAddress.town.name }}</text>
					<text v-if="shippingFee>=0" class="address-text" style="padding-left: 8px;">
						| 普通快递：<text style="color:#ff0000; margin: 0 3px;">{{shippingFee }}</text>元
					</text>
					<text v-if="shippingDesc && shippingDesc!==''" class="address-text" style="padding-left: 8px;">
						| {{ shippingDesc }}</text>
				</view>

				<!-- 数量选择 -->
				<view class="quantity-section">
					<view class="section-title">数量</view>
					<view class="quantity-control">
						<button class="quantity-btn" @click="decreaseQuantity">-</button>
						<input type="number" v-model="quantity" class="quantity-input" />
						<button class="quantity-btn" @click="increaseQuantity">+</button>
					</view>
				</view>

				<!-- 弹窗底部按钮 -->
				<view class="popup-actions">
					<button class="popup-add-cart" @click="confirmAddToCart">加入购物车</button>
					<button class="popup-buy-now" @click="confirmBuyNow">立即购买</button>
				</view>
			</view>
		</u-popup>

		<!-- 推荐产品 -->
		<view class="recommend-section">
			<view class="section-title">推荐产品</view>
			<view class="recommend-list">
				<view class="recommend-item" v-for="(item, index) in recommendProducts" :key="index"
					@click="goToProduct(item)">
					<image :src="$tools.buildUrl(item.white_back_ground_pic_url)" mode="aspectFill"
						class="recommend-image"></image>
					<text class="recommend-title">{{ item.spu_name }}</text>
					<view class="recommend-price">
						<text class="price">¥{{ item.price_min }}</text>
						<button class="recommend-add-btn" @click.stop="quickAdd(item)">+</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 产品参数 -->
		<view class="params-section">
			<view class="section-header" @click="toggleParams">
				<text class="section-title">产品参数</text>
				<u-icon :name="showParams ? 'arrow-up' : 'arrow-down'" size="16"></u-icon>
			</view>
			<view class="params-content" v-show="showParams">
				<view class="param-item" v-for="(param, index) in dataInfo.property_json" :key="index">
					<text class="param-label">{{ param.property_name }}</text>
					<text class="param-value">{{ param.property_value }}</text>
				</view>
			</view>
		</view>

		<!-- 产品详情 -->
		<view class="detail-section">
			<view class="section-title">产品详情</view>
			<view class="detail-images">
				<image v-for="(image, index) in dataInfo.desc_images" :key="index" :src="$tools.buildUrl(image.url)"
					mode="widthFix" class="detail-image"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				id: '', // 产品ID
				dataInfo: {}, // 商品详情
				defaultAddress: {}, // 默认收货地址
				currentImageIndex: 0,
				showSpecPopup: false,
				showParams: false,
				unit_price: 0,
				quantity: 1,
				selectedSpecs: 0,
				selectedDelivery: 0,
				deliveryOptions: [{
					value: 1,
					label: '快递寄送'
				}, {
					value: 1,
					label: '门店自提'
				}],
				shippingAddress: '',
				recommendProducts: [], // 推荐商品
				location: {
					latitude: 0,
					longitude: 0,
					province: '',
					city: '',
					town: '',
					address: ''
				},
				shippingFee: 0,
				freeDelivery: false,
				limitDelivery: false,
				shippingDesc: ''
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo', 'dealerInfo'])
		},
		onLoad(options) {
			if (options.id) {
				this.id = options.id;
				this.loadDataInfo();
			}
			if (options.inviteCode) {
				// 获取页面栈实例数组
				const pages = getCurrentPages();
				// 获取当前页面实例（最后一个元素）
				const currentPage = pages[pages.length - 1];
				// 获取页面路径
				const pagePath = currentPage.route;
				// 带有邀请码
				const inviteCode = options.inviteCode;
				this.$fenxiao.loadNewDirectid(inviteCode, pagePath);
			}
			// this.userLocation();
			// this.chooseLocation();			
			this.loadRecommend()
		},

		// 微信小程序分享配置
		onShareAppMessage() {
			// 分销员审核状态：-1待审核 0未审核 1审核中 2审核通过 2驳回
			if (!this.userInfo.check_status || this.userInfo.check_status !== 2) {
				return
			}
			// 获取页面栈实例数组
			const pages = getCurrentPages();
			// 获取当前页面实例（最后一个元素）
			const currentPage = pages[pages.length - 1];
			// 获取页面路径
			const pagePath = currentPage.route;
			if (!pagePath || pagePath === '') {
				pagePath = '/pages/index/index';
			}
			// 分享人信息（邀请码：inviteCode）
			let inviteCode = ''
			if (this.userInfo && Number(this.userInfo.id) > 0) {
				inviteCode = this.$secret.encryptAES(this.userInfo.id)
			}
			// 显示图片优先级: 商品 -- 店铺  -- 默认
			let imageUrl = ''
			if (this.dataInfo && this.dataInfo.white_back_ground_pic_url != '') {
				imageUrl = this.$tools.buildUrl(this.dataInfo.white_back_ground_pic_url)
			} else if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
				imageUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			} else {
				imageUrl = this.$tools.buildUrl('/static/images/product.png')
			}

			return {
				title: `${this.dealerInfo.shop_name} - 优质六堡茶专营`,
				path: `${pagePath}?id=${this.id}&inviteCode=${inviteCode}`,
				imageUrl: imageUrl,
				miniprogramType: 1,
				success: res => {
					// 用户点击了“发送”按钮（分享成功）
					// console.log('分享成功', res);
					// 任务类型：1 - 注册积分 2 - 推荐积分 3 - 分享积分 4 - 消费积分 5 - 签到积分
					this.$api.point.CompletePointsTask({
						task_type: 3,
						task_desc: `分享了${this.dealerInfo.shop_name} - ${this.dataInfo.spu_name}`
					}).then(res => {
						uni.showToast({
							title: res.msg,
							icon: 'success'
						})
					})
				},
				fail: err => {
					// 用户取消分享或发送失败
					// console.log('分享失败', err);
				}
			};
		},

		// 分享到朋友圈配置
		onShareTimeline() {
			// 分销员审核状态：-1待审核 0未审核 1审核中 2审核通过 2驳回
			if (!this.userInfo.check_status || this.userInfo.check_status !== 2) {
				return
			}
			// 分享人信息（邀请码：inviteCode）
			let inviteCode = ''
			if (this.userInfo && Number(this.userInfo.id) > 0) {
				inviteCode = this.$secret.encryptAES(this.userInfo.id)
			}
			// 显示图片优先级: 商品 -- 店铺  -- 默认
			let imageUrl = ''
			if (this.dataInfo && this.dataInfo.white_back_ground_pic_url != '') {
				imageUrl = this.$tools.buildUrl(this.dataInfo.white_back_ground_pic_url)
			} else if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
				imageUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			} else {
				imageUrl = this.$tools.buildUrl('/static/images/product.png')
			}

			return {
				title: `${this.dealerInfo.shop_name} - 优质六堡茶专营`,
				query: `id=${this.id}&inviteCode=${inviteCode}`,
				imageUrl: imageUrl,
				success: res => {
					// 用户点击了“发送”按钮（分享成功）					
					// console.log('分享成功', res);
					// 任务类型：1 - 注册积分 2 - 推荐积分 3 - 分享积分 4 - 消费积分 5 - 签到积分
					this.$api.point.CompletePointsTask({
						task_type: 3,
						task_desc: `分享了${this.dealerInfo.shop_name} - ${this.dataInfo.spu_name}`
					}).then(res => {
						uni.showToast({
							title: res.msg,
							icon: 'success'
						})
					})
				},
				fail: err => {
					// 用户取消分享或发送失败
					// console.log('分享失败', err);
				}
			};
		},

		methods: {
			loadDataInfo() {
				this.$api.good.GetProductInfo({
					id: this.id
				}).then(res => {
					this.dataInfo = res.data;
					// 商品SPU数组对象字段
					// 使用reduce找到具有最小custom_price_cny的项
					let minItem = this.dataInfo.skuArray.reduce((prev, current) => {
						return (prev.custom_price_cny <= current.custom_price_cny) ? prev : current;
					}, this.dataInfo.skuArray[0]); // 初始值设置为数组的第一个元素
					if (minItem) {
						this.selectedSpecs = this.dataInfo.skuArray.indexOf(minItem);
						this.unit_price = minItem.custom_price_cny;
					} else {
						this.selectedSpecs = 0
						this.unit_price = this.dataInfo.skuArray[0].custom_price_cny;
					}
					this.dataInfo.main_images = this.$tools.parseJsonObject(this.dataInfo.main_images);
					this.dataInfo.desc_images = this.$tools.parseJsonObject(this.dataInfo.desc_images);
					this.dataInfo.attribute_json = this.$tools.parseJsonObject(this.dataInfo.attribute_json);
					this.dataInfo.property_json = this.$tools.parseJsonObject(this.dataInfo.property_json);
					this.dataInfo.sku_property_json = this.$tools.parseJsonObject(this.dataInfo.sku_property_json);
					this.dataInfo.platform_attrs = this.$tools.parseJsonObject(this.dataInfo.platform_attrs);
					this.dataInfo.after_sale_service = this.$tools.parseJsonObject(this.dataInfo
						.after_sale_service);
					// 规格属性
					this.dataInfo.skuArray.forEach(skuitem => {
						skuitem.property_json = this.$tools.parseJsonObject(skuitem.property_json);
						skuitem.package_sku = this.$tools.parseJsonObject(skuitem.package_sku);
					})
					// 获取默认地址计算运费
					this.userDefaultAddress();

					this.$fenxiao.loadNewShop(this.dataInfo.company_id);
				})
			},
			userLocation() {
				// 用户当前位置
				uni.getLocation({
					type: 'wgs84', // 微信小程序必须用 'wgs84'，APP/H5建议 'gcj02'
					geocode: true, // APP端开启可返回地址信息（iOS需HBuilderX 3.0.0+）
					success: (res) => {
						// console.log('纬度:', res.latitude, '经度:', res.longitude);
						// APP端成功时 res.address 含详细地址
					},
					fail: (err) => {
						// console.error('定位失败:', err);
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						});
					}
				});
			},
			// 选择位置
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						// console.log('选择的位置：', res)
						this.location.latitude = res.latitude;
						this.location.longitude = res.longitude;
						this.location.address = res.address + res.name;
						// 可以根据选择的位置自动填充地址信息
						if (res.address) {
							// 解析地址信息
							this.parseAddress(res.address)
						}
					},
					fail: (err) => {
						// console.log('选择位置失败：', err)
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						})
					}
				})
			},

			// 解析地址
			parseAddress(address) {
				// 这里可以实现地址解析逻辑				
				if (address && address !== '') {
					// 正则匹配（适用于大多数中文地址）
					const match = address.match(/(.+省|.+自治区|.+市)?(.+市)?(.+区|.+县|.+旗)?/);
					if (match) {
						const province = match[1] || ''; // 广东省
						const city = match[2] || '直辖市'; // 深圳市
						const town = match[3] || ''; // 南山区
						this.location.province = province;
						this.location.city = city;
						this.location.town = town;
						this.location.address = this.location.address.replace(province + city + town, '')
						this.location.address = this.location.address.replace(province + town, '')
					}
				}
			},
			userDefaultAddress() {
				// 用户默认收货地址
				this.$api.user.GetDefaultAddress().then(res => {
					this.defaultAddress = res.data
					this.defaultAddress.mobile = this.$secret.decryptAES(this.defaultAddress.mobile)
					this.defaultAddress.address = this.$secret.decryptAES(this.defaultAddress.address)
					this.defaultAddress.province = this.$tools.parseJsonObject(this.defaultAddress.province)
					this.defaultAddress.city = this.$tools.parseJsonObject(this.defaultAddress.city)
					this.defaultAddress.town = this.$tools.parseJsonObject(this.defaultAddress.town)
					this.defaultAddress.street = this.$tools.parseJsonObject(this.defaultAddress.street)
					this.calculateFreight()
				})
			},
			calculateFreight() {
				// 根据运费模板和收货地址计算运费 
				if (!(this.defaultAddress && this.defaultAddress.id > 0)) {
					return;
				}
				if (!(this.dataInfo.freight_template && this.dataInfo.freight_template.id > 0)) {
					return;
				}
				this.shippingFee = 0;
				this.freeDelivery = false;
				this.shippingDesc = '';
				const province = this.defaultAddress.province
				const city = this.defaultAddress.city
				const town = this.defaultAddress.town
				const goodAmount = this.unit_price * this.quantity
				const totalWeight = parseFloat(this.dataInfo.skuArray[this.selectedSpecs].weight) * this.quantity
				const totalVolume = parseFloat(this.dataInfo.skuArray[this.selectedSpecs].volume) * this.quantity

				// 计价方式：1-按重量 2-按件数 3-按体积
				const calculate_type = this.dataInfo.freight_template.calculate_type
				// 运费类型-0:阶梯计价 1:固定运费 2:卖家包邮 3:货到付款
				const freight_rule_type = this.dataInfo.freight_template.rule_type
				// 规则类型（1:默认运费；2:指定地区运费；3:指定条件包邮；4:指定限售地区）
				let ruleArray = this.dataInfo.freight_template.ruleArray
				ruleArray.forEach(item => {
					item.rule_address = this.$tools.parseJsonObject(item.rule_address)
					item.rule_address.forEach(pcs => {
						const ii = item.rule_address.findIndex(o => o.code !== pcs.code && o.code
							.startsWith(pcs.code));
						if (ii >= 0) {
							pcs.hasChildren = true;
						} else {
							pcs.hasChildren = false;
						}
					});
					const new_rule_address = item.rule_address.filter(pcs => !pcs.hasChildren);
					item.rule_address = new_rule_address; // 只保留末级节点
				})

				// step1. 限售地区 [{ "code": "32", "name": "江苏省" }]
				this.limitDelivery = false;
				const limitArea = ruleArray.filter(item => item.rule_type === 4)
				if (limitArea && limitArea.length > 0) {
					limitArea.forEach(item => {
						const index1 = item.rule_address.findIndex(node => node.code === province.code || node
							.name === province.name);
						const index2 = item.rule_address.findIndex(node => node.code === city.code || node
							.name ===
							city.name);
						const index3 = item.rule_address.findIndex(node => node.code === town.code || node
							.name ===
							town.name);
						if (index1 >= 0 || index2 >= 0 || index3 >= 0) {
							this.limitDelivery = true;
						}
					})
				}
				if (this.limitDelivery) {
					this.shippingFee = 0;
					this.shippingDesc = '限售'
					return;
				}
				// step2. 卖家包邮 或 货到付款
				if (freight_rule_type >= 2) {
					this.freeDelivery = true;
					this.shippingFee = 0;
					this.shippingDesc = '卖家包邮'
					return;
				}
				// step3. 指定条件包邮
				this.freeDelivery = false;
				const baoyouArea = ruleArray.filter(item => item.rule_type === 3)
				if (baoyouArea && baoyouArea.length > 0) {
					baoyouArea.forEach(item => {
						const index1 = item.rule_address.findIndex(node => node.code === province.code || node
							.name === province.name);
						const index2 = item.rule_address.findIndex(node => node.code === city.code || node
							.name ===
							city.name);
						const index3 = item.rule_address.findIndex(node => node.code === town.code || node
							.name ===
							town.name);
						if (index1 >= 0 || index2 >= 0 || index3 >= 0) {
							// 满xx包邮 计量单位（1-元 2-kg 3-cm³）
							if (item.over_danwei === 1 && goodAmount >= item.over_number) {
								this.freeDelivery = true;
							} else if (item.over_danwei === 2 && totalWeight >= item
								.over_number) {
								this.freeDelivery = true;
							} else if (item.over_danwei === 2 && totalVolume >= item
								.over_number) {
								this.freeDelivery = true;
							}

							if (this.freeDelivery) {
								this.shippingDesc = '满' + ruleitem.over_number + (ruleitem.over_danwei === 1 ?
									'元' : ruleitem.over_danwei === 2 ? 'kg' : 'cm³') + '，包邮'
							}
						}
					})
				}
				if (this.freeDelivery) {
					this.shippingFee = 0;
					return;
				}
				// step4. 指定地区计算邮费（取最高）
				let isCharging = false;
				let maxChargingFreight = 0;
				const chargingArea = ruleArray.filter(item => item.rule_type === 2)
				if (chargingArea && chargingArea.length > 0) {
					chargingArea.forEach(item => {
						const index1 = item.rule_address.findIndex(node => node.code === province.code || node
							.name === province.name);
						const index2 = item.rule_address.findIndex(node => node.code === city.code || node
							.name ===
							city.name);
						const index3 = item.rule_address.findIndex(node => node.code === town.code || node
							.name ===
							town.name);
						if (index1 >= 0 || index2 >= 0 || index3 >= 0) {
							isCharging = true;
							// 阶梯计费 或 固定运费 calculate_type 计价方式：1-按重量 2-按件数 3-按体积
							let basicValue = 0;
							let thisChargingFreight = 0;
							if (calculate_type === 1) {
								basicValue = totalWeight;
							} else if (calculate_type === 2) {
								basicValue = this.quantity;
							} else {
								basicValue = totalVolume;
							}
							if (freight_rule_type === 0) {
								thisChargingFreight = item.first_price;
								basicValue -= parseFloat(item.first_unit);
								if (basicValue > 0 && parseFloat(item.add_unit) > 0) {
									// 向上取整
									thisChargingFreight += Math.ceil(basicValue / parseFloat(item.add_unit)) *
										parseFloat(item.add_price);
								}
							} else if (freight_rule_type === 1) {
								thisChargingFreight = item.fixed_amount;
							}

							if (thisChargingFreight > maxChargingFreight) {
								maxChargingFreight = thisChargingFreight;
							}
						}
					})
				}
				if (isCharging) {
					if (maxChargingFreight > this.shippingFee) {
						this.shippingFee = maxChargingFreight;
					}
					return;
				}

				// step5. 默认运费规则（取最高）
				let maxDefaultFreight = 0;
				const defaultArea = ruleArray.filter(item => item.rule_type === 1)
				if (defaultArea && defaultArea.length > 0) {
					defaultArea.forEach(item => {
						// 阶梯计费 或 固定运费 calculate_type 计价方式：1-按重量 2-按件数 3-按体积
						let basicValue = 0;
						let thisDefaultFreight = 0;
						if (calculate_type === 1) {
							basicValue = totalWeight;
						} else if (calculate_type === 2) {
							basicValue = this.quantity;
						} else {
							basicValue = totalVolume;
						}
						if (freight_rule_type === 0) {
							thisDefaultFreight = item.first_price;
							basicValue -= parseFloat(item.first_unit);
							if (basicValue > 0 && parseFloat(item.add_unit) > 0) {
								// 向上取整
								thisDefaultFreight += Math.ceil(basicValue / parseFloat(item.add_unit)) *
									parseFloat(item.add_price);
							}
						} else if (freight_rule_type === 1) {
							thisDefaultFreight = item.fixed_amount;
						}

						if (thisDefaultFreight > maxDefaultFreight) {
							maxDefaultFreight = thisDefaultFreight;
						}
					})
				}
				if (maxDefaultFreight > this.shippingFee) {
					this.shippingFee = maxDefaultFreight;
				}
			},
			loadRecommend() {
				// 商品推荐
				this.$api.good.GetProductList({
					page: 1,
					limit: 6,
					group_id: this.dataInfo.group_id
				}).then(res => {
					this.recommendProducts = res.data
				})
			},
			onSwiperChange(e) {
				this.currentImageIndex = e.detail.current
			},
			switchImage(index) {
				this.currentImageIndex = index
			},
			previewImage(image) {
				uni.previewImage({
					urls: this.dataInfo.main_images.map(item => item.url),
					current: image
				})
			},
			closeSpecPopup() {
				this.showSpecPopup = false
			},
			selectSpec(index) {
				// 选择商品规格
				this.selectedSpecs = index
				this.unit_price = this.dataInfo.skuArray[index].custom_price_cny
			},
			selectDelivery(index) {
				this.selectedDelivery = index
			},
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--
				}
			},
			increaseQuantity() {
				this.quantity++
			},
			confirmAddToCart() {
				// 选择规格后，确认加入购物车
				if (this.isLogin) {
					if (this.selectedSpecs < 0) {
						uni.showToast({
							title: '请选择商品规格',
							icon: 'none'
						})
						return
					}
					if (this.quantity < 1) {
						uni.showToast({
							title: '请输入购买数量',
							icon: 'none'
						})
						return
					}
					if (this.selectedDelivery < 0) {
						this.selectedDelivery = 0
					}
					this.$api.order.AddShoppingCart({
						spu_id: this.dataInfo.id,
						sku_id: this.dataInfo.skuArray[this.selectedSpecs].id,
						shop_id: this.dataInfo.skuArray[this.selectedSpecs].shop_id,
						store_id: this.dataInfo.skuArray[this.selectedSpecs].store_id,
						receive_type: this.deliveryOptions[this.selectedDelivery].value,
						quantity: this.quantity,
						unit_price: this.unit_price,
						tax_rate: 0
					}).then(res => {
						uni.showToast({
							title: res.msg,
							icon: 'success'
						})
						this.showSpecPopup = false
					})
				} else {
					uni.navigateTo({
						url: '/pages/login/login?isBack=true'
					})
				}
			},
			confirmBuyNow() {
				// 选择规格后，确认立即购买
				if (this.isLogin) {
					if (this.selectedSpecs < 0) {
						uni.showToast({
							title: '请选择商品规格',
							icon: 'none'
						})
						return
					}
					if (this.quantity < 1) {
						uni.showToast({
							title: '请输入购买数量',
							icon: 'none'
						})
						return
					}
					if (this.selectedDelivery < 0) {
						this.selectedDelivery = 0
					}
					const spu_id = this.dataInfo.id
					const sku_id = this.dataInfo.skuArray[this.selectedSpecs].id
					const receive_type = this.deliveryOptions[this.selectedDelivery].value
					uni.navigateTo({
						url: `/pages/order/payment?spu_id=${spu_id}&sku_id=${sku_id}&quantity=${this.quantity}&receive_type=${receive_type}`
					})
				} else {
					uni.navigateTo({
						url: '/pages/login/login?isBack=true'
					})
				}
			},
			addToFavorites() {
				// 点击收藏
				this.$api.user.AddFavorites({
					type_id: 1,
					data_id: this.dataInfo.id
				}).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'success'
					})
				})
			},
			contactService() {
				uni.showToast({
					title: '联系客服',
					icon: 'none'
				})
			},
			viewCart() {
				if (this.isLogin) {
					uni.switchTab({
						url: '/pages/cart/cart'
					})
				} else {
					uni.navigateTo({
						url: '/pages/login/login?isBack=true'
					})
				}
			},
			toggleParams() {
				this.showParams = !this.showParams
			},
			goToProduct(product) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${product.id}`
				})
			},
			quickAdd(product) {
				if (this.isLogin) {
					uni.navigateTo({
						url: `/pages/product/detail?id=${product.id}`
					})
				} else {
					uni.navigateTo({
						url: '/pages/login/login?isBack=true'
					})
				}
			},
			toUnlineStore() {
				uni.navigateTo({
					url: `/pages/store/list`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.product-detail-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding: 20rpx;
		padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
	}

	/* 商品图片区域 */
	.product-images {
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	.swiper {
		height: 600rpx;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 缩略图 */
	.thumbnail-list {
		display: flex;
		justify-content: center;
		padding: 20rpx;
		gap: 20rpx;
	}

	.thumbnail-item {
		width: 80rpx;
		height: 80rpx;
		border-radius: 8rpx;
		overflow: hidden;
		border: 2rpx solid transparent;
	}

	.thumbnail-item.active {
		border-color: #52a58a;
	}

	.thumbnail-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 商品信息区域 */
	.product-info {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.product-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		line-height: 1.4;
		margin-bottom: 30rpx;
	}

	.price-section {
		margin-bottom: 10rpx;
	}

	.price-label {
		font-size: 28rpx;
		color: #666;
	}

	.price-value {
		margin-bottom: 20rpx;
	}

	.current-price {
		font-size: 48rpx;
		color: #ff4757;
		font-weight: bold;
	}

	.activity-section {
		margin-bottom: 10rpx;
	}

	.activity-label {
		font-size: 28rpx;
		color: #666;
	}

	.activity-content {
		margin-bottom: 20rpx;
	}

	.activity-text {
		font-size: 28rpx;
		color: #52a58a;
	}

	/* 规格选择样式 */
	.spec-section {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.spec-header {
		margin-bottom: 30rpx;
	}

	.spec-label {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.spec-options {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.spec-option {
		flex: 1;
		padding: 20rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		text-align: center;
		transition: all 0.3s ease;
	}

	.spec-option.active {
		border-color: #1c705e;
		background-color: #f0f8f5;
	}

	.spec-text {
		font-size: 28rpx;
		color: #333;
	}

	.spec-option.active .spec-text {
		color: #1c705e;
		font-weight: 500;
	}

	.spec-combo {
		padding: 20rpx;
		margin-bottom: 20rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		text-align: center;
	}

	.spec-combo.active {
		border-color: #1c705e;
		background-color: #f0f8f5;
	}

	.combo-text {
		font-size: 28rpx;
		color: #333;
	}

	.spec-combo.active .combo-text {
		color: #1c705e;
		font-weight: 500;
	}

	/* 配送方式样式 */
	.delivery-section {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.delivery-header {
		margin-bottom: 30rpx;
	}

	.delivery-label {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.delivery-options {
		display: flex;
		gap: 20rpx;
	}

	.delivery-option {
		flex: 1;
		padding: 20rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		text-align: center;
		transition: all 0.3s ease;
	}

	.delivery-option.active {
		border-color: #1c705e;
		background-color: #f0f8f5;
	}

	.delivery-text {
		font-size: 28rpx;
		color: #333;
	}

	.delivery-option.active .delivery-text {
		color: #1c705e;
		font-weight: 500;
	}

	/* 发货信息样式 */
	.shipping-section {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.shipping-header {
		margin-bottom: 20rpx;
	}

	.shipping-label {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.shipping-content {
		padding: 20rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
	}

	.shipping-text {
		font-size: 28rpx;
		color: #666;
	}

	/* 数量选择样式 */
	.quantity-section {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.quantity-header {
		margin-bottom: 30rpx;
	}

	.quantity-label {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		background-color: #ffffff;
		font-size: 32rpx;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}

	.quantity-btn:disabled {
		color: #ccc;
		border-color: #f0f0f0;
		background-color: #f8f9fa;
	}

	.quantity-btn:not(:disabled):active {
		background-color: #f0f0f0;
	}

	.quantity-value {
		font-size: 32rpx;
		color: #333;
		min-width: 60rpx;
		text-align: center;
	}

	/* 底部操作栏 */
	.bottom-actions {
		padding: 20rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
	}

	.action-left {
		display: flex;
		align-items: center;
		gap: 40rpx;
		margin-right: 40rpx;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
	}

	.action-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.action-text {
		font-size: 20rpx;
		color: #666;
	}

	.action-right {
		flex: 1;
		display: flex;
		gap: 20rpx;
	}

	.add-cart-btn,
	.buy-now-btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		border: none;
	}

	.add-cart-btn {
		background-color: #ffffff;
		color: #52a58a;
		border: 2rpx solid #52a58a;
	}

	.buy-now-btn {
		background-color: #52a58a;
		color: #ffffff;
	}

	/* 规格弹窗 */
	.spec-popup {
		padding: 40rpx;
		max-height: 80vh;
		overflow-y: auto;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.spec-section {
		margin-bottom: 40rpx;
	}

	.spec-group {
		margin-bottom: 30rpx;
	}

	.spec-options {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.spec-option {
		padding: 20rpx 30rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #333;
	}

	.spec-option.active {
		border-color: #52a58a;
		color: #52a58a;
		background-color: #f0f8f5;
	}

	.spec-desc {
		font-size: 24rpx;
		color: #666;
		margin-top: 10rpx;
	}

	.delivery-section,
	.address-section,
	.quantity-section {
		margin-bottom: 40rpx;
	}

	.section-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.delivery-options {
		display: flex;
		gap: 20rpx;
	}

	.delivery-option {
		padding: 20rpx 30rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #333;
	}

	.delivery-option.active {
		border-color: #52a58a;
		color: #52a58a;
		background-color: #f0f8f5;
	}

	.address-text {
		font-size: 26rpx;
		color: #666;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		background-color: #ffffff;
		font-size: 32rpx;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.quantity-input {
		width: 120rpx;
		height: 60rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		text-align: center;
		font-size: 28rpx;
	}

	.popup-actions {
		display: flex;
		gap: 20rpx;
		margin-top: 40rpx;
	}

	.popup-add-cart,
	.popup-buy-now {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		border: none;
	}

	.popup-add-cart {
		background-color: #ffffff;
		color: #52a58a;
		border: 2rpx solid #52a58a;
	}

	.popup-buy-now {
		background-color: #52a58a;
		color: #ffffff;
	}

	/* 推荐产品 */
	.recommend-section {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.recommend-list {
		display: flex;
		gap: 20rpx;
		overflow-x: auto;
		padding: 20rpx 0;
	}

	.recommend-item {
		min-width: 200rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.recommend-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
	}

	.recommend-title {
		font-size: 24rpx;
		color: #333;
		text-align: center;
		margin-bottom: 12rpx;
		line-height: 1.3;
	}

	.recommend-price {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
	}

	.recommend-price .price {
		font-size: 28rpx;
		color: #ff4757;
		font-weight: bold;
	}

	.recommend-add-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background-color: #52a58a;
		color: #ffffff;
		border: none;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 产品参数 */
	.params-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	.section-header {
		padding: 40rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.params-content {
		padding: 0 40rpx 40rpx;
	}

	.param-item {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f8f8f8;
	}

	.param-item:last-child {
		border-bottom: none;
	}

	.param-label {
		font-size: 28rpx;
		color: #666;
	}

	.param-value {
		font-size: 28rpx;
		color: #333;
	}

	/* 产品详情 */
	.detail-section {
		background-color: #ffffff;
		padding: 40rpx;
	}

	.detail-images {
		margin-top: 20rpx;
	}

	.detail-image {
		width: 100%;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
	}

	.detail-image:last-child {
		margin-bottom: 0;
	}
</style>